package com.qf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.constans.SystemParameter;
import com.qf.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * 校验参数的过滤器
 */

@Component
public class ParameterFilter extends ZuulFilter {

    @Resource
    private RedisService redisService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //需要我们确定必要参数是否传递    将必须要的参数放入redis中方便动态修改

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        Set<String> commonsparameters = redisService.members(SystemParameter.APIPARAM);

        for (String commonsparameter : commonsparameters) {
            String parameter = request.getParameter(commonsparameter);
            if (parameter==null || "".equalsIgnoreCase(parameter)){
                currentContext.getResponse().setContentType("text/html;charset=utf-8");
                currentContext.setResponseBody("参数"+commonsparameter+"为毕传项，岂能为空！！");
                currentContext.setSendZuulResponse(false);
            }
        }

        return null;
    }
}
